package api;



import bean.login.LoginResponseBean;
import com.alibaba.fastjson.JSON;
import common.utils.JsonUtils;


import httpclient.HttpClientUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.cfg.WxCfg;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Map;

/**
 * Created by asus on 2018/9/29.
 */
@Service
public class LoginApi {

    private static final Logger logger = LoggerFactory.getLogger(LoginApi.class);

    @Autowired
    WxCfg wxCfg;

    /**
     * 小程序获取openid sessionKey
     *
     * @param code
     * @return
     * @throws Exception
     */
    public  LoginResponseBean getLoginInfo(String code) throws Exception {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxCfg.getApp_id() + "&secret=" + wxCfg.getApp_secret() + "&js_code=" + code + "&grant_type=authorization_code";
        logger.info("-----login----");
        Map map = HttpClientUtils.get(requestUrl);
        LoginResponseBean responseBean = new LoginResponseBean();
        responseBean = mapToBean(responseBean, map);
        logger.info("-----login---user-"+JsonUtils.toJson(responseBean));
        return responseBean;
    }


    public Map getPhone(String encryptedData, String sessionKey, String iv){
        String phoneInfo = this.decrypt(encryptedData,sessionKey,iv);
        Map map = (Map) JSON.parse(JsonUtils.stringToJson(phoneInfo));
        logger.warn(JsonUtils.toJson(map));
        return map;
    }

    /**
     * 微信小程序解密用户敏感数据获取用户信息
     *
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param sessionKey    数据进行加密签名的密钥
     * @param iv            加密算法的初始向量
     * @return
     */
    public String decrypt(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JsonUtils.toJson(result);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T mapToBean(T t, Map<Object, String> map) {
        try {
            // 获取javaBean属性
            BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
            // 创建 JavaBean 对象
            Object bean = t.getClass().newInstance();
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            if (propertyDescriptors != null && propertyDescriptors.length > 0) {
                String propertyName = null; // javaBean属性名
                Object propertyValue = null; // javaBean属性值
                for (PropertyDescriptor pd : propertyDescriptors) {
                    propertyName = pd.getName();
                    if (map.containsKey(propertyName)) {
                        propertyValue = map.get(propertyName);
                        pd.getWriteMethod().invoke(bean, new Object[]{propertyValue});
                    }
                }
                return (T) bean;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}



